<template>
	<div class="articlePost">

		<!-- 面包屑 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item>首页</el-breadcrumb-item>
			<el-breadcrumb-item>发布文章</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 主体 -->
		<div class="main_form">
			<el-form ref="form" :model="form" label-width="80px" :rules="rules">

				<el-form-item label="标题" prop="title">
					<el-input v-model="form.title"></el-input>
				</el-form-item>

				<el-form-item label="类型">
					<el-radio-group v-model="form.type">
						<el-radio :label="1">文章</el-radio>
						<el-radio :label="2">视频</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="栏目" prop="categories">
					<el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选
					</el-checkbox>
					<el-checkbox-group v-model="form.categories" @change="handleCheckedChange">
						<el-checkbox v-for="item in categoryList" :key="item.id" :label="item.id" name="type">
							{{item.name}}
						</el-checkbox>
					</el-checkbox-group>

				</el-form-item>


				<el-form-item label="内容">
					<!-- 富文本组件 -->
					<VueEditor v-if="form.type == 1" :config="config" ref="VueEditor" class="VueEditor" />

					<!-- type2 视频上传 -->
					<!-- action="http://157.122.54.189:9083/upload" -->
					<el-upload v-else class="upload-demo" action="http://157.122.54.189:9083/upload"
						:before-upload="videoBeforeUpload" :on-success="videoUploadSuccess" :headers="token">
						<el-button size="small" type="primary">点击上传视频</el-button>
						<div slot="tip" class="el-upload__tip">只能上传 MP4 / AVI 格式视频</div>
					</el-upload>
				</el-form-item>



				<!-- 封面组件 -->
				<el-form-item label="封面" class="cover_item">
					<el-upload 
					action="http://157.122.54.189:9083/upload" 
					list-type="picture-card" 
					:headers="token"
					:limit='3' 
					:on-success="handleSuccess" 
					:on-preview="handlePictureCardPreview"
					:on-remove="handleRemove"
					:file-list="form.cover"
					>
						<i class="el-icon-plus"></i>
					</el-upload>
					<el-dialog :visible.sync="coverUpload.dialogVisible">
						<img width="100%" :src="coverUpload.dialogImageUrl" alt="">
					</el-dialog>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" @click="onSubmit">立即创建</el-button>
					<el-button>取消</el-button>
				</el-form-item>

			</el-form>
		</div>

	</div>
</template>

<script>
	/* 富文本渲染器 */
	import VueEditor from 'vue-word-editor'
	import 'quill/dist/quill.snow.css'
	import {
		postArticleApi,
		getPostDetailsApi,
		updateArticleApi,
	} from '../../apis/news.js'
	import {
		getCategoryAPI
	} from '../../apis/category.js'
	import {
		getToken
	} from '../../utils/localData.js'

	export default {
		components: {
			VueEditor
		},


		data() {
			return {
				form: {
					title: '',
					categories: [], //栏目ID
					cover: [],
					type: 1,
					content: '',
				},
				checkAll: false,
				isIndeterminate: false,
				categoryList: [],
				rules: {
					title: [{
							required: true,
							message: '请输入标题',
							trigger: 'blur'
						},
						{
							min: 5,
							max: 50,
							message: '标题为5~50个字',
							trigger: 'blur'
						},
					],

					categories: [{
						type: 'array',
						required: true,
						message: '请至少选择一个栏目',
						trigger: 'change'
					}]
				},


				config: {
					// 上传图片的配置
					uploadImage: {
						url: this.$baseURL + "/upload", //文章上传到服务器端的处理路径
						name: "file", //后台所需要的参数的名称
						headers: {
							Authorization: getToken()
						},
						// res是结果，insert方法会把内容注入到编辑器中，res.data.url是资源地址
						uploadSuccess: (res, insert) => {
							if (res.data.message === '文件上传成功') {
								/* 插入到当前页面👇 */
								insert(this.$baseURL + res.data.data.url) //文件上传之后的回调，接收服务器响应回来的数据，根据服务器的地址进行填充
							} else {
								this.$message.error('文件上传失败！');
							}
						}
					},

					// 上传视频的配置

				},

				coverUpload: {
					dialogImageUrl: '',
					dialogVisible: false,
				},
				token: {
					Authorization: getToken()
				},
				videoType: ["video/avi", "video/mp4"],
			}
		},

		async created() {
			this.categoryList = (await getCategoryAPI()).data.data;
			this.categoryList = this.categoryList.splice(2);
		},

		async mounted() {
			const {
				id
			} = this.$route.params;
			if (id) {
				const articleDetail = (await getPostDetailsApi(id)).data.data;
				for (let key in this.form) {
					this.form[key] = articleDetail[key];
				}
				
				if(this.form.type === 1){
					/* 富文本 */
					this.$refs.VueEditor.editor.root.innerHTML = this.form.content;
				}

				
				/* 封面 */
				this.form.cover = this.form.cover.map(item => {
					item.url = this.$baseURL + item.url;
					return {
						id: item.id,
						url: item.url
					}
				})
			
				/* 栏目数组 */
				this.form.categories = this.form.categories.map(item => {
					return item.id
				})
				console.log(this.form);
			}

		},

		watch: {
			'form.categories': {
				handler: function(val){
					this.checkAll = val.length === this.categoryList.length;
					this.isIndeterminate = val.length > 0 && val.length < this.categoryList.length;
				}
			}
		},

		methods: {

			
			/* ↓↓组件方法↓↓ */
			onSubmit() {
				if (this.form.type == 1) {
					if (this.$refs.VueEditor.editor.getLength() > 1) {
						this.form.content = this.$refs.VueEditor.editor.root.innerHTML;
					} else {
						this.$message.error("发布文章内容不能为空！");
						return;
					}
				} else {

				}
				if (this.form.cover.length === 0) {
					this.$message.error("至少选择一张封面图");
					return;
				}
				this.$refs.form.validate(async (bool) => {
					if (bool) {
						/* 更正格式 */
						this.form.type = Number(this.form.type);
						this.form.categories = this.form.categories.map(item => {
							return {
								id: item
							}
						});
						
						let res;
						if(this.$route.params.id){
							res = await updateArticleApi(this.$route.params.id , this.form);
						}else{
							res = await postArticleApi(this.form);
						}

						console.log(res);
					}
				})
			},
			/* 栏目组件 */
			handleCheckAllChange(val) {
				const categoryNameList = this.categoryList.map(item => item.id)
				this.form.categories = val ? categoryNameList : [];
				this.isIndeterminate = false;
			},

			handleCheckedChange(val) {
				let checkedCount = val.length;
				this.checkAll = checkedCount === this.categoryList.length;
				this.isIndeterminate = checkedCount > 0 && checkedCount < this.categoryList.length;
			},

			/* 封面上传组件 */
			handlePictureCardPreview(file) {

			},

			handleRemove(file, fileList) {
				/* 删除一张重新将上传组件放出 */
				if (fileList.length < 3) {
					document.getElementsByClassName('el-upload--picture-card')[0].style.display = "";
				}
				/* 删除封面同步过滤表单内容 */
				const {
					id
				} = file.response.data;
				this.form.cover = this.form.cover.filter(item => {
					return item.id != id;
				})
				console.log(this.form.cover);
			},

			/* 超出上传个数 */
			handleSuccess(response, file, fileList) {
				if (response.message === "文件上传成功" && fileList.length === 3) {
					document.getElementsByClassName('el-upload--picture-card')[0].style.display = "none";
				} else {
					this.form.cover.push({
						id: response.data.id,
						url: "http://157.122.54.189:9083" + response.data.url,
					})
				}
			},


			/* 视频内容上传组件 */
			videoBeforeUpload(file) {
				console.log(file);
				// 中止本次的文件上传操作
				if (this.videoType.indexOf(file.type) === -1) {
					this.$message.error("仅支持 MP4 / AVI 视频格式");
					return false;
				}
			},


			videoUploadSuccess(response, file, fileList) {
				if (fileList.length > 1) {
					fileList.shift();
				}
				if (fileList.length === 1 && response.message === '文件上传成功') {
					this.form.content = "http://157.122.54.189:9083" + response.data.url;
				}
				//console.log(response, file, fileList);
			},

			/* 重置页面 */
			reSet(){
				location.reload();
			}
		},




	}
</script>

<style lang="less" scoped>
	.articlePost {

		.main_form {
			margin-top: 30px;
			background-color: #ffffff;
			padding: 50px;
			width: 70%;
			box-shadow: 5px 5px 20px 2px #777777;

			.cover_item {
				margin-top: 80px;
			}

			.el-form-item {
				padding: 10px 0;

				.VueEditor {
					height: 300px;
				}

			}

		}
	}
</style>
